//
//  MineController.m
//  XMLYFM
//
//  Created by dllo on 15/12/22.
//  Copyright © 2015年 zzl. All rights reserved.
//

#import "MineController.h"
#import "AboutViewController.h"
#import <MBProgressHUD.h>
#import <SDImageCache.h>
#import <Masonry.h>
#import "TZLoginViewController.h"
#import "CoreDataManager.h"
#import "User.h"


#define WIDTH  [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

@interface MineController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UITableView *mineTableView;

@property (nonatomic, strong) UIImageView *backImageView;

@property (nonatomic, strong) MBProgressHUD *hud;

@property(nonatomic,strong)UIImageView *MyHeadImg;
@property(nonatomic,retain)NSManagedObjectContext *managerObjectContext;
@property(nonatomic,retain)NSMutableArray *resultArr;//搜索结果

@property(nonatomic,strong)UIImage  *myPIc;
@end

@implementation MineController


-(void)viewWillAppear:(BOOL)animated
{
    NSString *logStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"logon"];
    NSString *perName = [[NSUserDefaults standardUserDefaults]objectForKey:@"person"];
    
    
    [self chaXun];
    
    
    for (User *user in _resultArr) {
        if ([user.name isEqualToString:perName]) {
            
            NSData *imageData = [NSData dataWithData:user.headPic];
            UIImage *image = [UIImage imageWithData: imageData];
            self.myPIc = image;
             break;
        }
       
    }

    
    if ([logStr isEqualToString:@"1"]) {
        
        self.nameLabel.text = perName;
        
        if (self.myPIc == NULL) {
            
            self.MyHeadImg.image = [UIImage imageNamed:@"MineHeader.png"];
        }
        else
        {
            self.MyHeadImg.image = self.myPIc;
        }
        
    }
    else
    {
        self.nameLabel.text = @"登陆";
        self.MyHeadImg.image = [UIImage imageNamed:@"MineHeader.png"];
    }

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.title = @"我的";
    _managerObjectContext = [[CoreDataManager shareManager]managedObjectContext];
    
        NSLog(@"🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶🐶%@",[[CoreDataManager shareManager]applicationDocumentsDirectory]);

    

//     NSLog(@"🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴🐴");
    
    
    
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注销" style:UIBarButtonItemStyleDone target:self action:@selector(leftAction:)];
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
    
    
#pragma mark - 创建UITableView
    
//    self.navigationController.navigationBar.hidden = YES;
    self.mineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 20 - 44 - 40) style:UITableViewStylePlain];
    [self.view addSubview:self.mineTableView];
    self.mineTableView.delegate = self;
    self.mineTableView.dataSource = self;
    [self.mineTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.mineTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.mineTableView.contentInset = UIEdgeInsetsMake(WIDTH * 0.62, 0, 0, 0);
    
    
#pragma mark - 创建图片
    self.backImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, - WIDTH * 0.62, WIDTH, WIDTH * 0.62)];
//    self.backImageView.image = [UIImage imageNamed:@"1.jpeg"];
    self.backImageView.backgroundColor = [UIColor colorWithRed:0.18 green:0.25 blue:0.31 alpha:1];
    self.backImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.mineTableView addSubview:self.backImageView];
    

    
    //tz 创建登陆头像
    self.MyHeadImg = [[UIImageView alloc]init];
    [self.backImageView addSubview:self.MyHeadImg];
    self.backImageView.userInteractionEnabled = YES;
   
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tagAction:)];
    [self.MyHeadImg addGestureRecognizer:tap];
    self.MyHeadImg.userInteractionEnabled = YES;
//    self.MyHeadImg.backgroundColor = [UIColor blackColor];
   [self.MyHeadImg mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.mas_equalTo(TZWIDTH/2 - 80/2);
       make.bottom.equalTo(self.backImageView).offset(-(TZWIDTH * 0.62/2 - 80/2));
       make.size.mas_equalTo(CGSizeMake(80, 80));

       
   }];
 
    self.nameLabel = [[UILabel alloc]init];
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    [self.backImageView addSubview:self.nameLabel];
    self.nameLabel.backgroundColor = [UIColor clearColor];
    self.nameLabel.textColor = [UIColor whiteColor];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.MyHeadImg.mas_bottom).offset(7);
        make.size.mas_equalTo(CGSizeMake(120,26));
        make.left.equalTo(self.MyHeadImg.mas_left).offset(-20);
        
    }];
    
    
 
}


-(void)chaXun
{

    //查询请求
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    
    //获取要查询的实体的描述
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:_managerObjectContext];
    
    //对fetchRequest 设置查询的实体
    [fetchRequest setEntity:entity];
    //第一个参数:按那个字段排序
    //第二个参数 是否升序的意思
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    //从数据库中搜索满足上面条件的元素
    NSArray *fetchedObjects = [_managerObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱🐱%@",error);
    }
    
    _resultArr = [NSMutableArray arrayWithArray:fetchedObjects];

}


//注销按钮

- (void)leftAction:(UIBarButtonItem *)btn
{
    [[NSUserDefaults standardUserDefaults]setValue:@"0" forKey:@"logon"];
    self.MyHeadImg.image = [UIImage imageNamed:@"MineHeader.png"];
    self.nameLabel.text = @"登陆";
    
    
}



-(void)tagAction:(UITapGestureRecognizer *)tap
{
    //状态
    NSString *logStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"logon"];
    
//    NSLog(@"sdfdsf");
    TZLoginViewController *login = [[TZLoginViewController alloc]init];
//    login.hidesBottomBarWhenPushed = YES;
//    ZHTabBarController *tabbar = [[ZHTabBarController alloc]init];
//    [tabbar isHiddenTabBar:YES withViewController:login];
    if ([logStr isEqualToString:@"0"]) {
        [self.navigationController pushViewController:login animated:YES];
    }
    else
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.allowsEditing = YES;
        picker.delegate = self;
        [self presentViewController:picker animated:YES completion:^{
            
            
        }];
    
    
    }
    
    

}



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
    NSString *perName = [[NSUserDefaults standardUserDefaults]objectForKey:@"person"];
    
    

   
    
      UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
      NSData *imageData = UIImagePNGRepresentation(image);
      self.MyHeadImg.image = image;
   
    [self chaXun];
        for (User *user in _resultArr) {
            if ([user.name isEqualToString:perName]) {
                user.headPic = imageData;
                [[CoreDataManager shareManager]saveContext];
                
                break;
            }
            
        }
    
    
    NSLog(@"info = %@",info);
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
   if (indexPath.row == 0)
    {
        cell.textLabel.text = @"清除缓存";
    }
    else if (indexPath.row == 1)
    {
        cell.textLabel.text = @"关于我们";
    }
    
    return cell;

}










-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    if (indexPath.row == 0) {
        NSUInteger size = [[SDImageCache sharedImageCache] getSize];
        float cacheSize = size / 1024.0 / 1024.0;
        NSString *string = [NSString stringWithFormat:@"缓存大小为%.2fMB", cacheSize];
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleActionSheet];
        
        [self presentViewController:alertC animated:YES completion:^{
        
        }];
        
        // 创建提示框按钮
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"清除缓存" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            // 清除缓存
            [[SDImageCache sharedImageCache] clearDisk];
            // hud单例
            self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            self.hud.labelText = @"清除缓存成功";
            self.hud.mode = MBProgressHUDModeText;
            [self.hud hide:YES afterDelay:1];
            
        }];
        // 创建提示框按钮
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        // 将按钮放在提示框上
        [alertC addAction:action];
        [alertC addAction:action1];
    }
    else if (indexPath.row == 1)
    {
        AboutViewController *aboutVC = [[AboutViewController alloc] init];
        [self.navigationController pushViewController:aboutVC animated:YES];
        
    }

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;

}



#pragma mark - scrollView协议方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    CGFloat y = scrollView.contentOffset.y;//加上导航栏高度,第一次是-200
    
    if (y < - WIDTH * 0.62) {
        CGRect frame = self.backImageView.frame;
        frame.origin.y = y;//偏移了多少,
        frame.size.height =  -y;//tablview向下偏移了多少,高度就是多少
        self.backImageView.frame = frame;
    }
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
